package com.ysl.study.designpattern.createmode.prototype;

import lombok.Data;

import java.io.*;
import java.util.List;

/**
 * 原型模式
 * 浅克隆
 * @author yangshanlin
 * @date 2023/2/22 11:27
 * @describe
 */
@Data
public class User implements Cloneable, Serializable {

    private int age;
    private String nickname;
    private String sex;
    private List<String> hobbyList;

    /**
     * 浅拷贝， 实现Cloneable接口，重写clone接口
     * @return
     */
    @Override
    public User clone() {
        try {
            User clone = (User) super.clone();
            // TODO: 复制此处的可变状态，这样此克隆就不能更改初始克隆的内部项
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    /**
     * 序列化实现深拷贝,需要实现序列化
     * @return
     */
    public User deepClone(){
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis =  new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (User) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
